package leetcode.string.palindrome;

import java.util.Arrays;

/**
 * 516. 最长回文子序列
 *
 * 最长的回文子序列的长度
 *
 */
public class LongestPalindromeSubseq {

    public static void main(String[] args) {
        LongestPalindromeSubseq solution = new LongestPalindromeSubseq();
        Integer len = solution.longestPalindromeSubseq("bbbab");
        solution.longestPalindromeSubseq0("bbbab");
        System.out.println(len);
    }

    /**
     * 动态规划实现
     *
     * @param s 字符串
     * @return  最长回文子序列的长度
     */
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        // 遍历的顺序
        for (int i = n - 1; i >= 0; i--) {
            dp[i][i] = 1;
            char c1 = s.charAt(i);
            for (int j = i + 1; j < n; j++) {
                char c2 = s.charAt(j);
                if (c1 == c2) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        System.out.println(Arrays.deepToString(dp));
        return dp[0][n - 1];
    }


    /**
     * 根据官方的动态规划解法 自己改写的
     * 改写了二维数组的遍历的顺序
     *
     * @param s 字符串
     * @return
     */
    public int longestPalindromeSubseq0(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int k = 0; k < n; k++) {
            dp[k][k] = 1;
        }

        for (int j = 1; j < n; j++) {
            char c1 = s.charAt(j);
            for (int i = j - 1; i >= 0; i--) {
                char c2 = s.charAt(i);
                if (c1 == c2) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        System.out.println(Arrays.deepToString(dp));
        return dp[0][n - 1];
    }
}
